﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Transactions;
using Framework.Common;

namespace Framework.Data.Implement
{
    /// <summary>
    /// 事务
    /// </summary>
    class GenericUnitOfWork : IUnitOfWork
    {

        TransactionScope transactionScope = null;

        #region constructor
        /// <summary>
        /// 构造器
        /// </summary>
        /// <param name="scope"></param>
        public GenericUnitOfWork(TransactionScope scope)
        {
            transactionScope = scope;
        }

        /// <summary>
        /// 构造器
        /// </summary>
        public GenericUnitOfWork()
        {
            transactionScope = new TransactionScope();
        }
        #endregion

        public bool IsInTransaction
        {
            get
            {
                return transactionScope != null;
            }
        }

        /// <summary>
        /// 提交事务
        /// </summary>
        public void CommitTransaction()
        {
            try
            {
                if (transactionScope != null)
                {
                    transactionScope.Complete();
                }
            }
            catch (TransactionAbortedException ex)
            {
                LogHelper.Error(ex.Message, ex);
            }
            catch (Exception ex)
            {
                LogHelper.Error("事务处理出错", ex);
            }
            finally
            {
                this.Dispose();
            }
        }

        /// <summary>
        /// Dispose
        /// </summary>
        public void Dispose()
        {
            if (transactionScope != null)
            {
                transactionScope.Dispose();
                transactionScope = null;
            }
        }
    }
}
